<template>
  <!--文件的上传 编辑回显 和下载  lingyaxin -->
  <el-upload
    ref="fileupload"
    class="upload-demo"
    action="#"
    :http-request="uploadFile"
    :before-upload="beforeUploadFile"
    :on-preview="onUploadPreview"
    :on-success="onUploadFileSuccess"
    :on-error="onUplodeFileError"
    :before-remove="handleBeforeRemove"
    :on-remove="handleRemove"
    :on-change="handleChange"
    :on-progress="handleOnProgress"
    multiple
    :file-list="fileList"
    :limit="5"
    :on-exceed="handleExceed"
  >
    <el-button size="small" type="primary">点击上传</el-button>
    <span slot="tip" class="el-upload__tip" style="padding-left:10px;color:red;font-size: 12px">(文件不超过30MB)</span>
  </el-upload>
</template>

<script>
// 附件上传
import { fileUpload, fileDownLoad, delFile } from '@/api/file/file.js'
export default {
  name: 'ImageUpload',
  props: {
    // 传入组件的类型（合同页面上传：contract类型，给上传的附件分类存放）
    category: {
      type: String,
      required: true
    },
    // 上传的附件回显
    editFileList: {
      type: Array,
      // 当为数组类型设置默认值时必须使用数组返回
      default: function() {
        return []
      }
    }
  },
  data() {
    return {
      // 用于存储附件的数组(只存id)
      fileIdsList: [],
      // 存放编辑 文件的集合（附件回显）
      fileList: [],
      // 删除的附件id
      deleteAttachListIds: ''
    }
  },
  computed: {
  },
  watch: {
    editFileList: function(val) {
      if (val !== undefined && val.length > 0) {
        this.fileList = JSON.parse(JSON.stringify(val))
        this.fileIdsList = JSON.parse(JSON.stringify(val))
      }
    },
    'fileIdsList'() {
      this.changeFileIdsList()
    }
  },
  // created() {
  //   var _this = this
  //   _this.fileList = []
  //   _this.fileIdsList = []
  // },
  methods: {
    // 附件上传之前调用的函数，控制附件上传的大小和格式
    beforeUploadFile(file) {
      const isLt30M = file.size / 1024 / 1024 < 30
      if (!isLt30M) {
        this.$message.error('上传头像图片大小不能超过 30MB!')
        return false
      }
      return true
    },
    // 文件上传时调动的方法
    handleOnProgress(event, file, fileList) {
      this.percent = Math.floor(event.percent)
    },
    // 自定义文件上传
    uploadFile(item) {
      var that = this
      // 传入文件的类型
      const category = that.category
      const formData = new FormData()
      formData.append('file', item.file)
      // const uid = item.file.uid
      fileUpload(formData, category).then(res => {
        item.onSuccess(res)
      }).catch((err) => {
        item.onError(err)
      })
    },
    // 上传的文件改变时调用的方法，附件新增 附件删除都会调用
    handleChange(file, fileList) {
      var _this = this
      _this.fileList = fileList
    },
    // 上传图片成功的回调
    onUploadFileSuccess(res, file) {
      var _this = this
      var fileData = {}
      var fileId = res.data.fileId
      var fileName = res.data.fileName
      var url = res.data.url
      var uid = file.uid
      fileData.fileId = fileId
      fileData.name = fileName
      fileData.url = url
      fileData.uid = uid
      // 填充上传文件列表
      _this.fileIdsList.push(fileData)
    },
    // 限制文件上传的个数
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 5 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`)
    },
    // 图片上传失败的回调
    onUplodeFileError(err, file, fileList) {
      var _this = this
      if (err.message === 'Network Error') {
        _this.$message.error('上传文件过大或者磁盘已满')
      } else {
        _this.$message.error('上传文件过大或者磁盘已满')
      }
    },
    // 上传的文件预览下载
    onUploadPreview(file) {
      // eslint-disable-next-line no-prototype-builtins
      var isRe = file.hasOwnProperty('response')
      var fileId
      var fileName
      if (isRe) {
        this.msgInfo('该文件应当先保存再下载')
      } else {
        fileId = file.fileId
        fileName = file.name
        fileDownLoad(fileId).then(res => {
          // 文件流下载
          this.downloadFileFlow(res, fileName)
        })
      }
    },
    // 文件删除之前操作
    handleBeforeRemove(file, fileList) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 在这里真正的处理图片列表
        this.handleRemove(file, fileList)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
      // 这是重点,不管上面的操作结果如何都返回false
      return false
      // var fdel = window.confirm('是否确定删除？')
      // if (fdel) { return true } else { return false }
    },
    // 文件删除
    handleRemove(file, fileList) {
      var _this = this
      // eslint-disable-next-line no-prototype-builtins
      var isRe = file.hasOwnProperty('response')
      var fileId = null
      if (isRe) {
        fileId = file.response.data.fileId
      } else {
        fileId = file.fileId
      }
      // _this.deleteById(fileId)
      // 删除用于存储fileIdsList中的值
      this.deleteAttachListIds += fileId + ','
      for (var j = 0; j < _this.fileIdsList.length; j++) {
        if (fileId === this.fileIdsList[j].fileId) {
          // 删除存放附件id数组中的id
          _this.fileIdsList.splice(j, 1)
        }
      }
      // 删除 控件本身filelist中的值
      for (var k = 0; k < _this.fileList.length; k++) {
        // eslint-disable-next-line no-prototype-builtins
        if (_this.fileList[k].hasOwnProperty('response')) {
          if (fileId === this.fileList[k].response.data.fileId) {
            // 删除存放附件id数组中的id
            _this.fileList.splice(k, 1)
          }
        } else if (fileId === this.fileList[k].fileId) {
          // 删除存放附件id数组中的id
          _this.fileList.splice(k, 1)
        }
      }
    },
    // 删除附件
    deleteById(fileId) {
      var _this = this
      delFile(fileId).then(resp => {
        if (resp) {
          // 删除用于存储fileIdsList中的值
          for (var j = 0; j < _this.fileIdsList.length; j++) {
            if (fileId === this.fileIdsList[j].fileId) {
              // 删除存放附件id数组中的id
              _this.fileIdsList.splice(j, 1)
            }
          }
          // 删除 控件本身filelist中的值
          for (var k = 0; k < _this.fileList.length; k++) {
            // eslint-disable-next-line no-prototype-builtins
            if (_this.fileList[k].hasOwnProperty('response')) {
              if (fileId === this.fileList[k].response.data.fileId) {
                // 删除存放附件id数组中的id
                _this.fileList.splice(k, 1)
              }
            } else if (fileId === this.fileList[k].fileId) {
              // 删除存放附件id数组中的id
              _this.fileList.splice(k, 1)
            }
          }
        } else {
          this.msgError(resp.message)
        }
      })
    },
    // 把上传的附件信息回传给父组件
    changeFileIdsList() {
      var _this = this
      var fileIdsList = _this.fileIdsList
      console.log(this.deleteAttachListIds)
      _this.$emit('getFileIdsList', fileIdsList, this.deleteAttachListIds)
    },
    // 清空上传的附件
    emptyFile() {
      var _this = this
      _this.fileList = []
      _this.fileIdsList = []
    },
    // 取消删除
    cancelDeleteByID() {
      var _this = this
      for (var i = 0; i < _this.fileList.length; i++) {
        // eslint-disable-next-line no-prototype-builtins
        if (_this.fileList[i].hasOwnProperty('response')) {
          _this.deleteById(_this.fileList[i].response.data.fileId)
        }
      }
      _this.emptyFile()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
